package com.example.forum.exception;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.stream.Stream;

/*
 * 处理全局异常
 *
 *  */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ResponseBody
    @ExceptionHandler(ApplicationException.class)
    public AppResult applicationException(ApplicationException e) {
        e.printStackTrace();
        log.error(e.getMessage());
        if (e.getErrorResult() != null) {
            return e.getErrorResult();
        }
        if (e.getMessage() == null || e.getMessage().trim().equals("")) {
            return AppResult.failed(ResultCode.ERROR_SERVICES);
        }
        return AppResult.failed(e.getMessage());
    }


    @ResponseBody
    @ExceptionHandler
    public AppResult exceptionHandler(Exception e) {
        log.error("e:" + e);
        Stream.of(e.getStackTrace()).forEach(System.out::println);
        return AppResult.failed(e.getMessage());
    }

}
